import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Input,
    Space,
    Radio,
    Upload,
    message,
    Spin,
} from 'antd'
import { PlusOutlined } from "@ant-design/icons";
import { Link } from 'react-router-dom'
import { useEffect, useState } from 'react';
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import styles from "./index.module.scss";
import Channel from '@/components/Channel';
import { addArticle, getArticle, editArticle } from '@/store/actions/article';
import { useDispatch } from 'react-redux';
import { useHistory, useParams } from 'react-router';
const Publish = () => {
    const dispatch = useDispatch()
    const history = useHistory()
    // 获取参数
    const params = useParams()
    // 表单，用于回显
    const [form] = Form.useForm();
    useEffect(() => {
        const setFormData = async () => {
            if(params.id){
                // 有id表示修改，回显数据
                setLoading(true)
                const { title, cover, content, channel_id } = await dispatch(getArticle(params.id));
                form.setFieldsValue({ title, content, channel_id })
                setType(cover.type)
                setFileList(cover.images.map(item => ({url: item})))
                setLoading(false)
            }else {
                // 在修改文章页面点击发布文章时需要重置数据
                form.resetFields()
                setType(1)
                setFileList([])
            }
        }
        setFormData()
    },[dispatch, form, params.id])
    // 设置类型
    const [type, setType] = useState(1);
    const onTypeChange = (e) => {
        setType(e.target.value);
        // 切换类型时清空文件列表
        setFileList([]);
    };
    // 上传文件
    const [fileList, setFileList] = useState([]);
    const onUploadChange = ({ fileList }) => {
        setFileList(fileList);
    };
    // 加载状态
    const [loading, setLoading] = useState(false)
    // 提交事件
    const onFinish = async (values, draft = false) => {
        if (type !== fileList.length) {
            return message.warning("请按照选择的封面类型上传图片");
        }
        // 组织提交数据
        const data = {
            ...values,
            cover: {
                type,
                // 后台需要[string]类型  
                images: fileList.map((item) => item.response.data.url || item.url),
            },
        };
        if(params.id) {
            // 有id表示编辑
            data.id = params.id
            await dispatch(editArticle(data, draft))
        }else {
            // 添加
            await dispatch(addArticle(data, draft));
        }
        if(draft) {
            message.success('保存成功')
        }else {
            message.success('提交成功')
        }
        history.push("/home/article");
    };
    // 存入草稿
    const saveDarft = async () => {
        try {
            const values = await form.validateFields()
            onFinish(values, true)
        } catch (error) {
            console.log(error);
        }
    }
    return (
        <div className={styles.root}>
            <Spin spinning={loading} size="large" tip="加载中">
                <Card
                    title={
                        <Breadcrumb>
                            <Breadcrumb.Item>
                                <Link to="/">首页</Link>
                            </Breadcrumb.Item>
                            <Breadcrumb.Item>
                                <Link to="/home/article">内容管理</Link>
                            </Breadcrumb.Item>
                            <Breadcrumb.Item>{params.id ? '修改文章' : '发布文章'}</Breadcrumb.Item>
                        </Breadcrumb>
                    }
                >
                    <Form form={form} onFinish={onFinish} labelCol={{ span: 4 }}>
                        <Form.Item
                            label="文章标题："
                            name="title"
                            rules={[{ required: true, message: "请输入文章标题" }]}
                        >
                            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
                        </Form.Item>
                        <Form.Item
                            label="所属频道："
                            name="channel_id"
                            rules={[{ required: true, message: "请选择所属频道" }]}
                        >
                            <Channel width={400} />
                        </Form.Item>
                        <Form.Item label="文章封面：">
                            {/* 一个FormItem只能有一个元素 */}
                            <Form.Item style={{ marginBottom: 0 }}>
                                <Radio.Group value={type} onChange={onTypeChange}>
                                    <Radio value={1}>单图</Radio>
                                    <Radio value={3}>三图</Radio>
                                    <Radio value={0}>无图</Radio>
                                </Radio.Group>
                            </Form.Item>
                            {/* 这个位置放Upload组件 */}
                            {type > 0 ? (
                                <div style={{ marginTop: 16 }}>
                                    <Upload
                                        name="image"
                                        listType="picture-card"
                                        action="http://geek.itheima.net/v1_0/upload"
                                        fileList={fileList}
                                        onPreview={() => { }}
                                        onChange={onUploadChange}
                                    >
                                        {fileList.length < type ? (
                                            <div>
                                                <PlusOutlined />
                                                <div style={{ marginTop: 8 }}>上传封面</div>
                                            </div>
                                        ) : null}
                                    </Upload>
                                </div>
                            ) : null}
                        </Form.Item>
                        <Form.Item
                            label="文章内容："
                            name="content"
                            initialValue=""
                            wrapperCol={{ span: 16 }}
                            rules={[{ required: true, message: "请输入文章内容" }]}
                        >
                            <ReactQuill placeholder="请输入文章内容" />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 4 }}>
                            <Space>
                                <Button type="primary" htmlType="submit">{params.id ? '修改文章' : '发布文章'}</Button>
                                <Button onClick={saveDarft}>存入草稿</Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Card>
            </Spin>
        </div>
    )
}

export default Publish